import { useCacheStore } from '../stores/cache.js'

/**
 * 缓存管理器
 * 提供缓存的自动清理、预加载等功能
 */
class CacheManager {
  constructor() {
    this.cacheStore = null
    this.cleanupInterval = null
    this.preloadInterval = null
    
    // 清理间隔时间（10分钟）
    this.CLEANUP_INTERVAL = 10 * 60 * 1000
    
    // 预加载间隔时间（30分钟）
    this.PRELOAD_INTERVAL = 30 * 60 * 1000
  }

  /**
   * 初始化缓存管理器
   */
  init() {
    this.cacheStore = useCacheStore()
    this.startCleanupTimer()
    this.startPreloadTimer()
    
    // 监听页面可见性变化
    this.setupVisibilityChangeListener()
    
    console.log('缓存管理器已初始化')
  }

  /**
   * 启动定时清理过期缓存
   */
  startCleanupTimer() {
    if (this.cleanupInterval) {
      clearInterval(this.cleanupInterval)
    }
    
    this.cleanupInterval = setInterval(() => {
      this.cleanupExpiredCache()
    }, this.CLEANUP_INTERVAL)
  }

  /**
   * 启动定时预加载
   */
  startPreloadTimer() {
    if (this.preloadInterval) {
      clearInterval(this.preloadInterval)
    }
    
    this.preloadInterval = setInterval(() => {
      this.preloadCriticalData()
    }, this.PRELOAD_INTERVAL)
  }

  /**
   * 清理过期缓存
   */
  cleanupExpiredCache() {
    if (!this.cacheStore) return
    
    try {
      const beforeStats = this.cacheStore.getCacheStats
      this.cacheStore.clearExpiredCache()
      const afterStats = this.cacheStore.getCacheStats
      
      console.log('缓存清理完成', {
        before: beforeStats,
        after: afterStats,
        timestamp: new Date().toISOString()
      })
    } catch (error) {
      console.error('清理过期缓存失败:', error)
    }
  }

  /**
   * 预加载关键数据
   */
  async preloadCriticalData() {
    if (!this.cacheStore) return
    
    try {
      // 动态导入 blogStore 避免循环依赖
      const { useBlogStore } = await import('../stores/blog.js')
      const blogStore = useBlogStore()
      
      // 预加载标签和分类数据（如果过期）
      const promises = []
      
      if (this.cacheStore.isCacheExpired('tags')) {
        promises.push(blogStore.getTags())
      }
      
      if (this.cacheStore.isCacheExpired('categories')) {
        promises.push(blogStore.getCategories())
      }
      
      if (promises.length > 0) {
        await Promise.all(promises)
        console.log('关键数据预加载完成', {
          timestamp: new Date().toISOString(),
          preloaded: promises.length
        })
      }
    } catch (error) {
      console.error('预加载关键数据失败:', error)
    }
  }

  /**
   * 监听页面可见性变化
   */
  setupVisibilityChangeListener() {
    if (typeof document === 'undefined') return
    
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState === 'visible') {
        // 页面变为可见时，检查并清理过期缓存
        setTimeout(() => {
          this.cleanupExpiredCache()
        }, 1000)
      }
    })
  }

  /**
   * 获取缓存统计信息
   */
  getCacheStats() {
    if (!this.cacheStore) return null
    return this.cacheStore.getCacheStats
  }

  /**
   * 手动清理所有缓存
   */
  clearAllCache() {
    if (!this.cacheStore) return
    
    this.cacheStore.clearAllCache()
    console.log('所有缓存已清理', {
      timestamp: new Date().toISOString()
    })
  }

  /**
   * 手动清理指定类型的缓存
   */
  clearCache(type, key = null) {
    if (!this.cacheStore) return
    
    this.cacheStore.clearCache(type, key)
    console.log(`缓存已清理: ${type}${key ? `:${key}` : ''}`, {
      timestamp: new Date().toISOString()
    })
  }

  /**
   * 销毁缓存管理器
   */
  destroy() {
    if (this.cleanupInterval) {
      clearInterval(this.cleanupInterval)
      this.cleanupInterval = null
    }
    
    if (this.preloadInterval) {
      clearInterval(this.preloadInterval)
      this.preloadInterval = null
    }
    
    console.log('缓存管理器已销毁')
  }

  /**
   * 设置缓存配置
   */
  updateConfig(config) {
    if (!this.cacheStore) return
    
    // 更新清理间隔
    if (config.cleanupInterval) {
      this.CLEANUP_INTERVAL = config.cleanupInterval
      this.startCleanupTimer()
    }
    
    // 更新预加载间隔
    if (config.preloadInterval) {
      this.PRELOAD_INTERVAL = config.preloadInterval
      this.startPreloadTimer()
    }
  }

  /**
   * 检查缓存健康状态
   */
  checkCacheHealth() {
    if (!this.cacheStore) return null
    
    const stats = this.cacheStore.getCacheStats
    const health = {
      totalCaches: 0,
      expiredCaches: 0,
      loadingCaches: 0,
      healthScore: 0
    }
    
    Object.entries(stats).forEach(([type, stat]) => {
      if (type === 'articles') {
        health.totalCaches += stat.count
        health.loadingCaches += stat.loading
      } else {
        if (stat.hasData) health.totalCaches++
        if (stat.isExpired) health.expiredCaches++
        if (stat.loading) health.loadingCaches++
      }
    })
    
    // 计算健康分数 (0-100)
    if (health.totalCaches > 0) {
      health.healthScore = Math.round(
        ((health.totalCaches - health.expiredCaches) / health.totalCaches) * 100
      )
    } else {
      health.healthScore = 100
    }
    
    return health
  }
}

// 创建单例实例
const cacheManager = new CacheManager()

export default cacheManager

// 导出便捷方法
export const initCacheManager = () => cacheManager.init()
export const getCacheStats = () => cacheManager.getCacheStats()
export const clearAllCache = () => cacheManager.clearAllCache()
export const clearCache = (type, key) => cacheManager.clearCache(type, key)
export const checkCacheHealth = () => cacheManager.checkCacheHealth()